<?php

namespace app\admin\dao;

use app\common\model\Consulting;
use app\common\model\ConsultingQuestion;
use app\common\model\ConsultingQuestionAnswer;
use ShidianUtil\Thinkphp\Dao\DaoTrait;

/**
 * ConsultingQuestionDao 数据访问对象
 * Class ConsultingQuestionDao
 * @package app\admin\dao
 * @method ConsultingQuestion findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method ConsultingQuestion insertActive(array $params, array $allow_field = [])
 * @method ConsultingQuestion updateActive(ConsultingQuestion $model, array $params, array $allow_field = [])
 * @method ConsultingQuestion findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method ConsultingQuestion updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(ConsultingQuestion $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class ConsultingQuestionDao
{
    use DaoTrait;

    /**
     * @var ConsultingQuestion
     */
    private $baseModel;

    /**
     * ConsultingQuestionDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = ConsultingQuestion::class;
    }

    public function listQuestions($categoryId, $startTime, $endTime, $kw, ?int $page, ?int $page_size): array
    {
        $query = ConsultingQuestion::when(is_id($categoryId), fn($query) => $query->where('categoryId', $categoryId))
            ->when(is_numeric($startTime), fn($query) => $query->where('created', '>=', $startTime))
            ->when(is_numeric($endTime), fn($query) => $query->where('created', '<=', $endTime))
            ->when(not_blank($kw), fn($query) => $query->search('id|ask', $kw))
            ->with([
                'member' => fn($query) => $query->shortMember(),
                'lawyer' => fn($query) => $query->shortMember(),
                'category' => fn($query) => $query->field(['id', 'name']),
            ])
            ->order('ord', 'ASC')
            ->order('id', 'DESC')
            ->paging($page, $page_size);

        return listOutput($query, $page_size);
    }

    public function findQuestion($id): ?ConsultingQuestion
    {

        $record = ConsultingQuestion::where('id', $id)
            ->with([
                'member' => fn($query) => $query->shortMember()->field(['phone']),
                'category' => fn($query) => $query->field(['id', 'name']),
            ])
            ->find();

        if (is_null($record)) {
            return null;
        }

        $consultingArr = Consulting::where('questionId', $id)
            ->where('lawyerId', '<>', '0')
            ->field(['id', 'lawyerId'])
            ->with([
                'lawyer' => fn($query) => $query->shortLawyer(),
                'questionAnswer' => fn($query) => $query->where('questionId', $id),
                'messages' => fn($query) => $query->where('senderType', 'member')->where('senderMemberType', '1')->where('messageType', 'text')->order('id', 'ASC')
            ])
            ->hidden(['messages'])
            ->order('id', 'ASC')
            ->select()
            ->each(function (Consulting $consulting) use ($id) {
                if (is_null($consulting->questionAnswer)) {
                    // 加载律师全部文字回复
                    $answer = $consulting->messages->reduce(function ($carry, $item) use (&$answer) {
                        if (is_null($carry)) {
                            return $item->content->text;
                        }
                        return $carry . "\r\n" . $item->content->text;
                    });
                    $consulting->setRelation('questionAnswer', new ConsultingQuestionAnswer([
                        'questionId' => $id,
                        'consultingId' => $consulting->id,
                        'answer' => $answer,
                        'isShow' => 0,
                        'created' => $consulting->created,
                    ]));
                }
            })
            ->filter(function (Consulting $consulting) {
                $questionAnswer = $consulting->getRelation('questionAnswer');
                return $questionAnswer && not_blank($questionAnswer->answer);
            })->values();

        $record->setRelation('consultingArr', $consultingArr);

        return $record;
    }
}
